package cn.wolfcode.interceptor;

import cn.wolfcode.domain.Result;
import cn.wolfcode.util.JwtUtils;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token =  request.getHeader("token");
        try {
            JwtUtils.parseJwt(token);
            return true;
        }catch (Exception e){
            response.setContentType("application/json;charset=utf-8");
            Result result = Result.noLogin();
            String jsonString = JSON.toJSONString(result);
            response.getWriter().write(jsonString);
            return false;
        }
    }
}
